//
// Created by Mr.Optimist on 2022/2/12.
//

#include "Texture.h"
#include "stb_image/stb_image.h"

Texture::Texture(const std::string &path)
        : m_RendererID(0), m_FilePath(path), m_LocalBuffer(nullptr), m_Width(0), m_Height(0), m_BitPerPixel(0) {
    stbi_set_flip_vertically_on_load(1);                                                // 垂直反转，OPENGL左下原点
    m_LocalBuffer = stbi_load(path.c_str(), &m_Width, &m_Height, &m_BitPerPixel, 4);    // 读取文件的宽高并存入

    GLCall(glGenTextures(1, &m_RendererID));
    GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID));

    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));   // 设置缩小采样
    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));   // 设置放大采样
    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));        // S方向截断
    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));        // T方向截断

    GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer));
    GLCall(glBindTexture(GL_TEXTURE_2D, 0));

    if(m_LocalBuffer)
        stbi_image_free(m_LocalBuffer);
}

Texture::~Texture() {
     GLCall(glDeleteTextures(1, &m_RendererID));    // 从GPU删除
}

void Texture::Bind(unsigned int slot) const {
    GLCall(glActiveTexture(GL_TEXTURE0 + slot));    // Texture到不同的槽
    GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID));
}

void Texture::UnBind() const {
    GLCall(glBindTexture(GL_TEXTURE_2D, 0));
}
